package com.nekonomics
package api.route

import api.dto.request.AddCartReq
import api.dto.response.RspEncoder.*
import domain.service.CartService
import domain.service.util.TokenService
import domain.validation.RequestValidator

import zio.*
import zio.http.*
import zio.http.Method.*
import zio.http.codec.PathCodec.*
import zio.json.*

object CartRoute {
  val routes = baseApiPath / "cart" / Routes(
    POST / "add-item" -> handler { (req: Request) =>
      for {
        body <- req.body.asString
        addCart <- ZIO.fromEither(body.fromJson[AddCartReq])
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        cartItemId <- ZIO.serviceWithZIO[CartService](_.addItem(userId, addCart))
        rsp = cartItemId.toRsp.toJson
      } yield Response.json(rsp)
    },

    GET / "items" -> handler { (req: Request) =>
      for {
        jwt <- extractJwt(req)
        userId <- ZIO.serviceWithZIO[TokenService](_.verifyToken(jwt))
        pageNum <- extractParam[Int](req)("pageNum")
        pageSize <- extractParam[Int](req)("pageSize")
        _ <- RequestValidator.checkPageReq(pageNum, pageSize)
        items <- ZIO.serviceWithZIO[CartService](_.cartItems(userId, pageNum, pageSize))
        rsp = items.toRsp.toJson
      } yield Response.json(rsp)
    }
  )



}
